package worker;

import Servlet.MyServletContextListener;
import Settings.KeyMap;
import Settings.ServerData;
import Settings.TestInfo;
import database.Database;
import database.LoadFromDatabase;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.json.simple.*;
import util.ClientInfo;
import util.UniqueUtil;

public class TerMessageProcessor {

    static Logger logger = Logger.getLogger(TerMessageProcessor.class);
    int lengthOfFile;

    public static JSONObject processData(HttpServletRequest request) throws Exception {

        JSONObject obj = new JSONObject();
        String query_type = request.getParameter("queryType");


        if (query_type.equals("request_appid")) {

            if (checkApplicationValidity()) {
                String app_version = request.getParameter("appVersion");
                String app_id = UniqueUtil.getUniqueString();

                obj.put("appID", app_id);

                createUser(app_id, app_version);

            } else {
                throw new Exception("Application not valid");
            }
        } else if (query_type.equals("request_sessionid")) {

            String appID = request.getParameter("appID");
            if (checkUserValidity(appID)) {
                String sessionID = UniqueUtil.getUniqueString();
                String MNC = request.getParameter("mnc");
                String MCC = request.getParameter("mcc");
                String GSM = request.getParameter("gsm");
                String clientIP = request.getParameter("clientIP");
                String serverIP = request.getParameter("serverIP");

                createSession(sessionID, appID, MNC, MCC, GSM, clientIP, serverIP);

                ServerData.sessionMaps.put(sessionID, System.currentTimeMillis());

                obj.put("sessionID", sessionID);

            } else {
                throw new Exception("User not valid");
            }

        } else if (query_type.equals("request_test")) {
            String sessionID = request.getParameter("sessionID");

            if (checkSessionValidity(sessionID)) {
                String testType = request.getParameter("testType");
                if (testType.equals("basic")) {
                    JSONArray list = new JSONArray();
                    ArrayList<TestInfo> testSettingsObjects = ServerData.getTestInfolist();
                    for (int i = 0; i < testSettingsObjects.size(); i++) {
                        if(testSettingsObjects.get(i).basicAppStatus.equalsIgnoreCase("inactive")) {
                            continue;
                        }
                        JSONObject jObj = new JSONObject();
                        jObj.put("protocolName", testSettingsObjects.get(i).protocol_name);
                        jObj.put("protocolID", testSettingsObjects.get(i).protocol_id);
                        jObj.put("port", testSettingsObjects.get(i).port);
                        jObj.put("transportLayerProtocol", testSettingsObjects.get(i).transmission_protocol);
                        jObj.put("fileContent", testSettingsObjects.get(i).fileContentClient);
                        jObj.put("fileContentClient", testSettingsObjects.get(i).fileContentClient);
                        jObj.put("fileContentServer", testSettingsObjects.get(i).fileContentServer);
                        list.add(jObj);
                    }

                    obj.put("test_list", list);

                } else if (testType.equals("advanced")) {

                    int protocolID = Integer.parseInt(request.getParameter("protocolID"));
                    boolean flag = false;
                    ArrayList<TestInfo> testSettingsObjects = ServerData.getTestInfolist();
                    for (int i = 0; i < testSettingsObjects.size(); i++) {
                        if (testSettingsObjects.get(i).protocol_id == protocolID) {

                            flag = true;
                            obj.put("protocolName", testSettingsObjects.get(i).protocol_name);
                            obj.put("protocolID", testSettingsObjects.get(i).protocol_id);
                            obj.put("port", testSettingsObjects.get(i).port);
                            obj.put("transportLayerProtocol", testSettingsObjects.get(i).transmission_protocol);
                            obj.put("fileContent", testSettingsObjects.get(i).fileContentClient);
                            obj.put("fileContentClient", testSettingsObjects.get(i).fileContentClient);
                            obj.put("fileContentServer", testSettingsObjects.get(i).fileContentServer);
                            //System.out.println(obj.toJSONString());
                            //System.out.println(obj.toString());
                            
                        }
                    }
                    
                    if(!flag)
                    {
                        throw new Exception("protocolID not found");
                    }

                } else {
                    throw new Exception("No test type specified");
                }
            } else {
                throw new Exception("session not valid");
            }
        } else if (query_type.equals("request_advanced_info")) {

            String appID = request.getParameter("appID");

            if (checkUserValidity(appID)) {
                JSONArray list = new JSONArray();
                ArrayList<TestInfo> testSettingsObjects = ServerData.getTestInfolist();
                for (int i = 0; i < testSettingsObjects.size(); i++) {
                        JSONObject jObj = new JSONObject();
                        jObj.put("protocolName", testSettingsObjects.get(i).protocol_name);
                        jObj.put("protocolID", testSettingsObjects.get(i).protocol_id);
                        jObj.put("port", testSettingsObjects.get(i).port);
                        jObj.put("transportLayerProtocol", testSettingsObjects.get(i).transmission_protocol);
                        list.add(jObj);
                }

                obj.put("test_list", list);
            }

        } else if (query_type.equals("test_result")) {
            String sessionID = request.getParameter("sessionID");
            if (checkSessionValidity(sessionID)) {
                String appID = request.getParameter("appID");
                int testProtocolID = Integer.parseInt(request.getParameter("testProtocol"));
                String serverIP = request.getParameter("serverIP");
                String clientIP = request.getParameter("clientIP");
                String serverPort = request.getParameter("serverPort");
                String clientPort = request.getParameter("clientPort");
                int dataSize = Integer.parseInt(request.getParameter("dataSize"));
                int tripTime = Integer.parseInt(request.getParameter("tripTime"));
                String testType = request.getParameter("testType");
                String isSuccessfulStr = request.getParameter("testSuccessful");
                String clientToServerResult = request.getParameter("clientToServerResult");
                String serverToClientResult = request.getParameter("serverToClientResult");
                ClientInfo clieninfoObj = MyServletContextListener.clientInfoMg.putQuery(clientIP);
                
                //logger.debug(clieninfoObj.ISP+" "+clieninfoObj.Country);
                
                boolean isSuccessful;
                if (isSuccessfulStr.equals("true")) {
                    isSuccessful = true;
                } else {
                    isSuccessful = false;
                }


                createTestResult(sessionID, appID, testProtocolID, serverIP, clientIP, serverPort, clientPort, dataSize, tripTime, isSuccessful,testType,clieninfoObj.ISP,clieninfoObj.Country,clientToServerResult,serverToClientResult);
                obj.put("dumpSuccessful", "true");

            } else {
                throw new Exception("session not valid");
            }

        } else if (query_type.equals("session_terminate")) {
            String sessionID = request.getParameter("sessionID");

            if (checkSessionValidity(sessionID)) {

                String emailID = request.getParameter("emailID");
                if (!emailID.equals("null")) {
                    createEmail(sessionID, emailID);
                    obj.put("dumpSuccessful", "true");
                }
                database.Database.sessionInvalidate(sessionID);
                ServerData.sessionMaps.remove(sessionID);
                obj.put("sessionRemoved", "true");

            } else {
                throw new Exception("session not valid");
            }
        } else if (query_type.equals("insert_basic_test_setttings")) {
        } else if (query_type.equals("update_basic_test_setttings")) {
        } else if (query_type.equals("delete_basic_test_setttings")) {
        } else if (query_type.equals("init")) {
            //loading Server information from DB
            if (LoadFromDatabase.getInstance().loadServerSettings()) {
                logger.debug("Successfully Loaded Server Information");
                System.out.println(Settings.ServerData.settings.get(KeyMap.SERVER_VERSION));
                logger.debug("Server Version: " + Settings.ServerData.settings.get(KeyMap.SERVER_VERSION));
            } else {
                logger.fatal("Failed to load Server Information");
            }
            //loading basic test settings from DB

            if (LoadFromDatabase.getInstance().loadBasicTestSettings()) {
                logger.debug("Successfully Loaded Basic Test Settings. Number of Total Settings: " + ServerData.testSettingsObjects.size());

            } else {
                logger.fatal("Failed to load Basic Test Settings");
            }

        } else if (query_type.equals("reinit")) {
        } else if (query_type.equals("shutdown")) {
            //OpenInternetServerImplementation.getInstance(request.getServletContext()).shutDown();
        } else {
            throw new Exception("query type not matched!");
        }

        return obj;
    }

    //*********************************************** DB *********************************/
    public static boolean checkApplicationValidity() {
        return true;
    }

    public static boolean checkUserValidity(String appid) {
        if (Database.checkUser(appid)) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean checkSessionValidity(String sessionid) {
        if (Database.checkSession(sessionid)) {
            return true;
        } else {
            return false;
        }
    }

    public static void createUser(String appid, String appVersion) {
        Database.createUser(appid, appVersion);
    }

    public static void createSession(String sessionId, String appID, String MNC, String MCC, String GSM, String clientIP, String serverIP) {
        Database.createSession(sessionId, appID, MNC, MCC, GSM, clientIP, serverIP);
    }

    public static void createTestResult(String sessionID, String appID, int testProtocolID, String serverIP, String clientIP, String serverPort, String clientPort, int dataSizeInByte, int tripTime, boolean isSuccessful, String testType, String ISP, String Country, String clientToServerResult, String serverToClientResult) {
        Database.createTestResult(sessionID, appID, testProtocolID, serverIP, clientIP, serverPort, clientPort, dataSizeInByte, tripTime, isSuccessful,testType,ISP,Country,clientToServerResult,serverToClientResult);
    }

    public static void createEmail(String sessionID, String email) {
        Database.createEmail(sessionID, email);
    }
}

    //******************************************** DB ****************************************/
